<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="130px">
      <el-form-item label="补料编码" prop="supplyCode">
        <el-input v-model="queryParams.supplyCode" placeholder="请输入补料编码" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>

      <el-form-item label="生产工单编码" prop="workorderCode">
        <el-input v-model="queryParams.workorderCode" placeholder="请输入生产工单编码" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <!-- <el-form-item label="审核人" prop="checkUser">
        <el-input
          v-model="queryParams.checkUser"
          placeholder="请输入审核人"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item> -->
      <el-form-item label="补料时间" prop="supplyTime">
        <el-date-picker clearable v-model="queryParams.supplyTime" type="date" value-format="yyyy-MM-dd HH:mm:ss" placeholder="请选择补料时间"></el-date-picker>
      </el-form-item>
      <!-- <el-form-item label="审核时间" prop="checkTime">
        <el-date-picker
          clearable
          v-model="queryParams.checkTime"
          type="date"
          value-format="yyyy-MM-dd HH:mm:ss"
          placeholder="请选择审核时间"
        ></el-date-picker>
      </el-form-item> -->
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="manageQuery({}, '生产补料_填报补料单', 'add')" v-hasPermi="['produce:feed:add']">新增</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:supply:export']"
        >导出</el-button>
      </el-col> -->
      <!-- <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar> -->
    </el-row>

    <el-table v-loading="loading" :data="supplyList" @selection-change="handleSelectionChange" height="calc(100vh - 280px)">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" align="center" width="50px">
        <template slot-scope="scope">
          <span>{{ scope.$index + 1 }}</span>
        </template>
      </el-table-column>
      <el-table-column label="补料编码" align="center" width="160px" prop="supplyCode">
        <template slot-scope="scope">
          <el-link type="primary" style="font-size:12px;vertical-align: baseline;" @click="handleCheck(scope.row)">{{
            scope.row.supplyCode }}</el-link>
        </template>
      </el-table-column>
      <el-table-column label="生产工单" align="center" prop="workorderCode" />
      <el-table-column label="状态" align="center" prop="workflowStatus">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.supply_workflow_status" :value="scope.row.workflowStatus" />
        </template>
      </el-table-column>
      <el-table-column label="申请补料时间" align="center" prop="supplyTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.supplyTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="申请人" align="center" prop="createBy" />
      <el-table-column label="审核人" align="center" prop="checkUser" />
      <el-table-column label="审核时间" align="center" prop="checkTime" />
      <el-table-column label="领料状态" align="center" prop="isIssue">
        <template slot-scope="scope">
          <span>{{ scope.row.isIssue == '0' ? '未领料' : scope.row.isIssue == '1' ? '全部领料' : scope.row.isIssue ==
            '2' ? "部分领料" : "--" }}</span>
        </template>
      </el-table-column>
      <el-table-column label="补料原因" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="saveToErp(scope.row)" v-hasPermi="['mes:k3cloud:proMaterialSupplyToErp:saveToErp']" v-if="scope.row.isIssue == 1&&scope.row.toErpStatus==0">上传ERP</el-button>
          <el-button size="mini" type="text" icon="el-icon-edit" @click="manageQuery(scope.row, '生产补料_填报补料单', 'edit')" v-hasPermi="['produce:feed:edit']" v-if="scope.row.workflowStatus == 1">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="manageQuery(scope.row, '生产补料_填报补料单', 'del')" v-hasPermi="['produce:feed:remove']" v-if="scope.row.workflowStatus == 1">删除</el-button>
          <el-button size="mini" type="text" @click="manageQuery(scope.row, '生产补料_补料审核', 'affirm')" v-if="scope.row.workflowStatus == 2">确认补料</el-button>
          <!-- <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleApproval(scope.row)"
            v-hasPermi="['system:supply:approval']"
            v-if="scope.row.supplyStatus==1"
          >创建审批流</el-button> -->
          <el-button size="mini" type="text" icon="el-icon-edit" @click="manageQuery(scope.row, '生产补料_生产领料', 'issue')" v-hasPermi="['produce:pickList:create']" v-if="scope.row.workflowStatus == 3">生成生产领料单</el-button>
          <el-button size="mini" type="text" icon="el-icon-printer" @click="getPrint(scope.row)" v-hasPermi="['produce:feed:print']" v-if="scope.row.workflowStatus == 3 || scope.row.workflowStatus == 4">打印补料单</el-button>
          <!-- <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleCheckDetail(scope.row,'2')"
            v-hasPermi="['system:supply:approval']"
            v-if="scope.row.isExamine==0 "
          >审批</el-button> -->
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handlePushDown(scope.row)" v-hasPermi="['produce:feed:Push']" v-if="scope.row.workflowStatus == 1 || scope.row.workflowStatus == 2 || scope.row.workflowStatus == 5">下推</el-button>

        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" />

    <!-- 添加或修改生产补料单对话框 optType add 新增 update 更新 -->
    <div v-if="open">
      <el-dialog :visible.sync="open" width="960px" append-to-body>
        <template v-slot:title>
          <b v-if="optType === 'check'">{{ title }}</b>
          <span v-if="optType !== 'check'">{{ title }}</span>
        </template>
        <el-form ref="form" :model="form" :rules="rules" label-width="120px">
          <el-tag size="large" style="font-size: 20px;">基本信息</el-tag>
          <hr />
          <el-row>
            <el-col :span="10">
              <el-form-item label="补料编码" prop="supplyCode">
                <el-input v-model="form.supplyCode" placeholder="请输入补料编码" v-if="optType === 'add'" />
                <span v-if="optType === 'update' || optType === 'check'">{{ form.supplyCode }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label-width="80">
                <el-switch v-model="autoGenFlag" active-color="#13ce66" active-text="自动生成" @change="handleAutoGenChange(autoGenFlag)" v-if="optType !== 'update' && optType !== 'check'"></el-switch>
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item label="生产工单" prop="workorderCode">
            <el-input v-model="form.workorderCode" placeholder="请输入生产工单" style="width:300px" v-if="optType !== 'check'" />
            <!--      @keyup.enter.native="handleQueryMaterialList"
              @change="handleQueryMaterialList" -->
            <span v-if="optType === 'check'">{{ form.workorderCode }}</span>
          </el-form-item>
          <el-form-item label="BOM版本" prop="bomItemCode">
            <el-input v-model="form.bomItemCode" placeholder="请输入BOM版本" style="width:300px" v-if="optType !== 'check'" />
            <!--      @keyup.enter.native="handleQueryMaterialList"
              @change="handleQueryMaterialList" -->
            <span v-if="optType === 'check'">{{ form.workorderCode }}</span>
          </el-form-item>
          <el-form-item label="补料原因" prop="remark">
            <el-input v-model="form.remark" placeholder="请输入补料原因" v-if="optType !== 'check'" style="width:300px" />
            <span v-if="optType === 'check'">{{ form.remark }}</span>
          </el-form-item>
          <!-- <el-row>
            <el-col :span="12">
              <el-form-item label="仓库信息" prop="warehouseId">
                <el-select
                  clearable
                  v-model="form.warehouseId"
                  placeholder="请选择仓库信息"
                  v-if="optType!=='check'"
                >
                  <el-option
                    v-for="(item,index) of warehouseList"
                    :key="index"
                    :label="item.warehouseName"
                    :value="item.warehouseId"
                  >{{item.warehouseName}}</el-option>
                </el-select>
                <span v-if="optType==='check'">{{form.warehouseName}}</span>
              </el-form-item>
            </el-col>
          </el-row> -->
        </el-form>
        <div v-if="personList.length > 0">
          <el-tag size="large" style="font-size: 20px;">审批流信息</el-tag>
          <hr />
        </div>
        <el-steps :active="stepResult == 'REFUSE' ? activeStep : activeStep" align-center>
          <el-step v-for="item in personList" :key="item.userMobile" :title="item.userNickname" :description="item.resultName" :status="item.result == 'REFUSE' ? 'error' : ''"></el-step>
        </el-steps>
        <el-tag size="large" style="font-size: 20px;">物料信息</el-tag>
        <hr />
        <!-- <el-tabs type="border-card" >
        <el-tab-pane label="详情">-->
        <supply-detail v-if="open" ref="supplyDetail" @onSelected="onSelected" :optType="optType" :parentId="parentId"></supply-detail>
        <!-- </el-tab-pane>
        
        </el-tabs>-->

        <div slot="footer" class="dialog-footer" v-if="optType !== 'check'">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </el-dialog>
    </div>

    <SupplyDetails ref="supplyDetails" @onSelected="onSelected" :supplyId="parentId"></SupplyDetails>
    <PrintChild v-if="openPrint" ref="printChild"></PrintChild>
    <ProcessMaintenance v-if="openRequisitionDetail" ref="processMaintenance" @getList="getList"></ProcessMaintenance>
  </div>
</template>

<script>
import {
  listSupply,
  getSupply,
  delSupply,
  addSupply,
  updateSupply,
  addSupplyBatchInfo,
  updateSupplyBatchInfo,
  getSupplyApproval,
  getApprovalList,
  getWareHouseList,
  supplyProcess,
  pushDownSupply,
  confirmedFeedSupply,
  saveToErp
} from "@/api/mes/pro/supply";
// 按钮权限
import {
  selectUserRole,
} from "@/api/mes/pro/workorder";
import supplyDetail from "./supplyDetail.vue";
import SupplyCheck from "./supplyCheck.vue";
import SupplyDetails from "./detail.vue";
import { genCode } from "@/api/mes/md/rule";
import PrintChild from "./print/print.vue";
// 生成领料单页面./components/processMaintenance.vue
import ProcessMaintenance from "../workorder/components/processMaintenance.vue";
import saleOutVue from '../../wm/deliverygoods/saleOut.vue';
export default {
  components: { supplyDetail, SupplyDetails, PrintChild, ProcessMaintenance },
  name: "Supply",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,

      openRequisitionDetail: false,
      // 总条数
      total: 0,
      // 生产补料单表格数据
      supplyList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      selectedRows: null,
      //新增or更新
      optType: null,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        supplyCode: null,
        workorderId: null,
        workorderCode: null,
        checkUser: null,
        supplyTime: null,
        checkTime: null
      },
      autoGenFlag: false,
      // 表单参数
      form: {},
      openPrint: false,
      //生产补料id
      parentId: "",
      // 表单校验
      rules: {
        supplyCode: [
          { required: true, message: "补料编码不能为空", trigger: "blur" }
        ],
        workorderCode: [
          { required: true, message: "生产工单不能为空", trigger: "blur" }
        ],
        bomItemCode: [
          { required: true, message: "BOM版本不能为空", trigger: "blur" }
        ],
        remark: [
          { required: true, message: "补料原因不能为空", trigger: "blur" }
        ],
        supplyTime: [
          { required: true, message: "补料时间不能为空", trigger: "blur" }
        ]
      },
      //审批人
      personList: [],
      //处于哪个环节
      activeStep: null,
      stepResult: null,
      warehouseList: []
    };
  },
  dicts: ['supply_workflow_status'],
  created() {
    this.getList();
  },
  methods: {
    saveToErp(data) {
      this.loading = true
      saveToErp(data.id).then(msg => {
        console.log(msg);
        if (msg.code == 200) {
          this.getList()
          this.loading = false
          this.$message.success("操作成功！");
        } else {
          this.loading = false
        }
      }).catch(err => {
        this.loading = false
      })

    },
    /** 查询生产补料单列表 */
    getList() {
      this.loading = true;
      listSupply(this.queryParams).then(response => {
        this.supplyList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
      getWareHouseList({}).then(response => {
        this.warehouseList = response.data;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        supplyCode: null,
        workorderId: null,
        workorderCode: null,
        checkUser: null,
        supplyTime: null,
        checkTime: null,
        remark: null,
        createTime: null,
        createBy: null,
        updateTime: null,
        updateBy: null,
        processInstanceId: null,
        warehouseId: null
      };
      this.resetForm("form");
      this.autoGenFlag = false;
      this.personList = [];
      this.activeStep = null;
      this.stepResult = null;
      this.parentId = "";
      this.optType = null;
      this.selectedRows = [];
    },
    //根据工单查询所有物料
    handleQueryMaterialList() {
      console.log(this.form.workorderCode, "asdfghjk==========");
      this.$refs.supplyDetail.refreshMaterialList(this.form.workorderCode);
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    // manage
    manageQuery(row, name, type) {
      selectUserRole(name).then((res) => {
        if (type == 'add') {
          this.handleAdd()
        } else if (type == 'edit') {
          this.handleUpdate(row)
        } else if (type == 'del') {
          this.handleDelete(row)
        } else if (type == 'affirm') {
          this.handleAffirm(row)
        } else if (type == 'issue') {
          this.handleMeterial(row)
        }

      }).catch(() => {
        //  this.$modal.msgError("此用户暂时没有权限");
        return "false"
      });
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.selectedRows = [];
      this.reset();
      this.open = true;
      this.optType = "add";
      this.title = "添加生产补料单";
      this.$nextTick(() => {
        this.$refs.supplyDetail.init(this.form, this.optType);
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.selectedRows = [];
      const id = row.id || this.ids;
      this.reset();
      getSupply(id).then(response => {
        console.log("111111111", response);
        this.form = response.data;
        this.open = true;
        this.optType = "update";
        this.parentId = id;
        this.title = "修改生产补料单";
        this.$nextTick(() => {
          this.$refs.supplyDetail.init(this.form, this.optType);
        });
      });
    },
    /** 查看详情按钮操作 */
    handleCheck(row) {
      this.parentId = row.id;
      console.log(this.parentId);
      this.$refs.supplyDetails.showFlag = true;
      this.selectedRows = [];
      // const id = row.id || this.ids
      // getSupply(id).then(response => {
      //   this.form = response.data;
      //   this.open = true;
      //   this.optType='check';
      //   this.parentId=id;
      //   this.title = "查看生产补料单";
      //   if(this.form.processInstanceId!=undefined&&this.form.processInstanceId!=null){
      //     getApprovalList(id).then(response => {
      //      this.personList=response.data.personList;
      //      for(const key in this.personList){
      //         if(this.personList[key].result!=undefined){
      //           if(this.personList[key].result=='AGREE'){
      //             this.personList[key].resultName='同意'
      //           }
      //           else if(this.personList[key].result=='REFUSE'){
      //             this.personList[key].resultName='拒绝'
      //           }
      //         }

      //       }
      //      this.activeStep=response.data.step;
      //      this.stepResult=response.data.supplyResult;
      //   });
      //   }
      // });
    },
    /** 审批流操作 */
    handleApproval(row) {
      this.selectedRows = [];
      const id = row.id || this.ids;
      this.reset();
      getSupply(id).then(response => {
        this.form = response.data;
        getSupplyApproval(response.data).then(response => {
          console.log("生成审批流成功");
          this.$modal.msgSuccess("创建审批流成功");
          this.getList();
        });
      });
    },
    /** 提交按钮 */
    submitForm() {
      console.info("this.selectedRows===>" + JSON.stringify(this.selectedRows));
      if (this.selectedRows == null || this.selectedRows.size == 0) {
        this.$notify({
          title: "提示",
          type: "warning",
          message: "请至少选择一条数据!"
        });
        return;
      }
      console.info("this.selectedRows===>", JSON.stringify(this.selectedRows));
      for (let i = 0; i < this.selectedRows.length; i++) {
        if (this.selectedRows[i].itemAmount == null || this.selectedRows[i].itemAmount == "") {
          this.selectedRows[i].itemAmount = 1
        }
      }
      this.$refs["form"].validate(valid => {
        if (valid) {
          let reqParam = {
            baseInfo: this.form,
            detailList: this.selectedRows
          };
          if (this.optType !== "check") {
            if (this.form.id != undefined) {
              updateSupplyBatchInfo(reqParam).then(response => {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              });
            } else {

              //新增
              addSupplyBatchInfo(reqParam).then(response => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              });
            }
          }
        }
      });
    },
    onSelected(selectedRows) {
      this.selectedRows = selectedRows;
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      const supplyCode = row.supplyCode
      this.$modal
        .confirm('是否确认删除生产补料单编号为"' + supplyCode + '"的数据项？')
        .then(function () {
          return delSupply(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => { });
    },
    // 生成生产领料单
    handleMeterial(row) {
      this.openRequisitionDetail = true;
      console.log(row, "领料单编号的row");
      this.$nextTick(() => {
        this.$refs.processMaintenance.init(row);
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "system/supply/export",
        {
          ...this.queryParams
        },
        `supply_${new Date().getTime()}.xlsx`
      );
    },

    handleAutoGenChange(autoGenFlag) {
      if (autoGenFlag) {
        genCode("MATERIAL_SUPPLY").then(response => {
          this.form.supplyCode = response;
        });
      } else {
        this.form.supplyCode = null;
      }
    },
    // 审核
    handleCheckDetail(row) {

    },
    getPrint(row) {
      this.openPrint = true
      this.$nextTick(() => {
        this.$refs.printChild.init(row);
      })
    },
    // 下推 
    handlePushDown(row) {
      // pushDownSupply
      let query = { ...row }
      query.flowType = row.workflowStatus == 1 ? 'tbbld' : row.workflowStatus == '2' || row.workflowStatus == '5' ? 'blsh' : ''
      this.$modal
        .confirm(
          '是否确认下推补料编码为"' + row.supplyCode + '"的数据项？'
        )
        .then(function () {
          return pushDownSupply(query);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("下推成功");
        })
        .catch(() => { });
    },
    handleAffirm(row) {
      this.$modal
        .confirm(
          '是否确认补料编码为"' + row.supplyCode + '"的数据项？'
        )
        .then(function () {
          return confirmedFeedSupply(row);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("确认审核成功");
        })
        .catch(() => { });
    },
  }
};
</script>
<!-- <style scoped lang="scss">
.title{
  margin-top: -60px;
}
</style> -->
